package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;

import com.itheima.utils.BaseContext;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @date 2023/4/17
 */
@RequestMapping("/order")
@RestController
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 下单操作
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        //1.调用service的下单方法
        ordersService.submit(orders);
        //2.返回结果
        return R.success("下单成功！");
    }

    /**
     * 歷史訂單查詢
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> getPage(@RequestParam(defaultValue = "1")Integer page,
                                      @RequestParam(defaultValue = "5")Integer pageSize){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> ordersWrapper = new LambdaQueryWrapper<>();
        //獲取id（自定義的工具類---baseContext）
        Long userId = BaseContext.getValue();
        ordersWrapper.eq(Orders::getUserId,userId)
                .orderByDesc(Orders::getOrderTime);
        List<Orders> ordersList = ordersService.list(ordersWrapper);
        ordersService.page(ordersPage,ordersWrapper);//設置分頁和查詢給ordersPage

        //開始設置OrdersDto的Page
        Page<OrdersDto> ordersDtoPage = new Page<>(page,pageSize);
        //複製分頁而不複製其中的内容
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<OrdersDto> ordersDtoList = ordersList.stream().map((orders) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders,ordersDto);
            List<OrderDetail> orderDetailList = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, orders.getId()));
            ordersDto.setOrderDetails(orderDetailList);
            ordersDto.setUserName(orders.getConsignee());//將收貨人設爲用戶名
            return ordersDto;
        }).collect(Collectors.toList());
        //page
        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);
    }

    @PostMapping("/again")
    public R<String> again(@RequestBody OrdersDto ordersDto){

        return ordersService.again(ordersDto);
    }






    /**
     * 訂單分頁查詢
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page<Orders>> getOrdersPage(@RequestParam(defaultValue = "1")Integer page,
                                         @RequestParam(defaultValue = "10")Integer pageSize,
                                         String number,
                                         LocalDateTime beginTime,
                                         LocalDateTime endTime){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> ordersWrapper = new LambdaQueryWrapper<>();
        //根據傳入的條件進行查詢
        ordersWrapper.like(number!=null,Orders::getNumber,number)
                .between(beginTime!=null&&endTime!=null,Orders::getOrderTime,beginTime,endTime)
                .orderByDesc(Orders::getOrderTime);
        List<Orders> ordersList = ordersService.list(ordersWrapper);
        ordersList = ordersList.stream().map((orders) -> {
            orders.setUserName(orders.getConsignee());
            return orders;
        }).collect(Collectors.toList());
        ordersPage.setRecords(ordersList);
        ordersService.page(ordersPage,ordersWrapper);
//        return R.success(ordersPage);
        return R.success(ordersPage);
    }

    /**
     * 修改訂單狀態
     * @param orders
     * @return
     */
    @PutMapping()
    public R<String> changeOrders(@RequestBody Orders orders){
        Orders ordersServiceById = ordersService.getById(orders.getId());
        ordersServiceById.setStatus(orders.getStatus());
        ordersService.updateById(ordersServiceById);
        return R.success("修改成功");
    }
}
